import 'package:get/get.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';

class SplashController extends GetxController {
  @override
  void onReady() {
    super.onReady();
    checkLogin();
  }

  Future<void> checkLogin() async {
    String token = await SPUtils.getString(SPUtils.TOKEN);
    if (token.isEmpty) {
      goToPage(Routes.login);
      return;
    }
    getCompanyList();
  }

  Future<void> getCompanyList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_LIST,
      {},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is List) {
          List<CompanyEntity> companyList = data.map((element) {
            return CompanyEntity().fromJson((element as Map<String, dynamic>));
          }).toList();
          if (companyList.isEmpty) {
            ToastUtils.toast("您没有用油客户权限,请联系管理员");
            return;
          }
          checkCompany(companyList);
        }
      },
    );
  }

  Future<void> checkCompany(List<CompanyEntity> companyList) async {
    String companyId = await SPUtils.getString(SPUtils.COMPANY_ID);
    if (companyId.isEmpty) {
      SPUtils.saveString(SPUtils.COMPANY_ID, companyList.first.id ?? "");
    } else {
      if (!hasSameCompany(companyId, companyList)) {
        SPUtils.saveString(SPUtils.COMPANY_ID, companyList.first.id ?? "");
      }
    }
    goToPage(Routes.main, arguments: companyList);
  }

  bool hasSameCompany(String companyId, List<CompanyEntity> companyList) {
    for (int i = 0; i < companyList.length; i++) {
      String id = companyList[i].id ?? "";
      if (companyId == id) {
        return true;
      }
    }
    return false;
  }

  void goToPage(String page, {dynamic arguments}) {
    Future.delayed(Duration(seconds: 1)).then((value) {
      Get.offNamedUntil(page, (route) => false, arguments: arguments);
    });
  }
}
